/**
 * 登录模块，提供登录相关业务功能
 * 
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "msgServ","ajaxServ","formServ","tabServ","datagridServ","commonSelect","commonServ","userPasswordModule"], 
	function($,msgServ,ajaxServ,formServ,tabServ,datagridServ,commonSelect,commonServ,userPassword) {

	'use strict';

	var currentBizcode, menuTab,
		$ma, $userMenu,
		permissionUrl="/biz/getPermissions.action",
		currentUser,
		//当前tab页title
		currentTitle,
		//应用根节点
		rootPath='',
		
		//页面行数定义
		pageRows = 15,
		
		//当前tab页模块配置信息
		currentModuleConfig,
	
		activeMenuitems 
		
	var logoutUrl='/biz/logout.action'
	var getCurrentUserUrl='/biz/getCurentUser.action'
	var private_method = {
		savePassword:function(){
			var _usr =public_method.getCurrentUser();
			
			var _param = {
				user		: _usr,
				rootPath	: '/' + public_method.getRootPath()
			}
			userPassword.popInit(_param)
		},
		
		closeTabs:function(title,index){
			if(title!=null){
				switch($.trim(title)){
					case '业务资源':
						requirejs(['permissionModule'],function(modu){
							modu.destory()
						})
						break;
				}
			}
		},
		/**
		 * 主页面导航栏按钮监听函数
		 */
		accordionClick : function(e) {
			
			var _url = ''
			var _text = ''
			if(e!=null){
				e.preventDefault();
				e.stopPropagation();
				_url = $(e.currentTarget).attr('targetUrl');
				currentBizcode = $(e.currentTarget).attr('fullBizcode')
				_text = e.currentTarget.text
				if((_text==null)||($.trim(_text).length<=0)){
					if(e.currentTarget.innerText){
						if (window.console) {
						console.info('innerText: ' + e.currentTarget.innerText);
						}
						_text = e.currentTarget.innerText
					}
					
				}
				//保存当前tab页
				currentTitle = _text;
				var _options = {
					target : 'centerTabs',
					title : _text,
					tabUrl : '/'+rootPath+_url,
					tools : []
				};
				if (_url) {
//					tabServ.addFrameTab(_options);
					tabServ.addHrefTab(_options)
				}
				
				
			}
			return false;

//			event.preventDefault();
		},
		
		menuItemClick:function(e){
			$.messager.progress({				
				msg:'loading...'
			});
			var _url = ''
			var _text = ''
			if(e && e.id){
				
				
				var _config = public_method.getModuConf(e.id),
				currentBizcode = _config.fullBizcode
				_url = _config.pageURL;
				_text = e.text?$.trim(e.text):null
				
				if(_text && _text.length>0){
					//保存当前tab页
					currentTitle = _text;
					var _options = {
						target : 'centerTabs',
						title : _text,
						tabUrl : '/'+rootPath+_url,
						tools : []
					};
					if (_url) {
	//					tabServ.addFrameTab(_options);
						tabServ.addHrefTab(_options)
					}
				}				
				
			}else{
				$.messager.progress('close');
			}
			return false;
		},
		menuInitEasyUi:function(i,e){
			var menulist ="<div class=\"well well-small\">";
				if(e.child && e.child.length>0){
					$.each(e.child,function(ci,ce){
						if(window.console){
							console.log('init child menu ...')
						}
						if(ce && ce.type=='F'){
							var effort=ce.name+"||"+ce.iconCls+"||"+ce.url;
							menulist+="<a href=\"javascript:void(0);\" class=\"accordion-btn easyui-linkbutton\" data-options=\"plain:true,iconCls:'"+ce.iconcls + "'\"  bizcode='" + ce.bizcode + "'\"  fullBizcode='" + ce.fullBizcode +  "'\"  targeturl='" + ce.pageURL +"' data-type='accordion-btn'\>" +ce.name+"</a><br/>";
							public_method.setModuConf(ce.fullBizcode,ce);
							public_method.setModuleNameConfig($.trim(ce.name),ce.fullBizcode)
						}
					});
				}
				menulist+="</div>";
				$ma.accordion('add', {
		            title: e.name,
		            content: menulist,
					border:false,
		            iconCls: e.iconCls,
		            selected: false
		        });
			
		},
		menuInitBootstrap:function(i,e){
			
			var menulist ="<div>";
				if(e.child && e.child.length>0){
					$.each(e.child,function(ci,ce){
						
						if(window.console){
							console.log('init child menu ...')
						}
						//判断是否菜单类型
						if(ce && ce.type=='F'){
							var effort=ce.name+"||"+ce.iconCls+"||"+ce.url;
							menulist+="<a href=\"javascript:void(0);\" class=\"accordion-btn easyui-linkbutton\" data-options=\"plain:true,iconCls:'"+ce.iconcls + "'\"  bizcode='" + ce.bizcode + "'\"  fullBizcode='" + ce.fullBizcode +  "'\"  targeturl='" + ce.pageURL +"' data-type='accordion-btn'\>" +ce.name+"</a><br/>";
							public_method.setModuConf(ce.fullBizcode,ce);
							public_method.setModuleNameConfig($.trim(ce.name),ce.fullBizcode)
						}
					});
				}
				menulist+="</div>";
				$ma.accordion('add', {
		            title: e.name,
		            content: menulist,
					border:false,
		            iconCls: e.iconCls,
		            selected: false
		        });
			
		}
		,
		
		initStartMenu:function(i,e){
			
			var rootMenu = $('#main-mm');
			
			var _parentParam = {
					text: e.name
				}
			if(e.pageURL && e.pageURL.indexOf('/')>=0){
				_parentParam.id = e.fullBizcode
				
				public_method.setModuConf(e.fullBizcode,e);
					public_method.setModuleNameConfig($.trim(e.name),e.fullBizcode)
			}
			var parentMenuItem = $(rootMenu).menu('appendItem', _parentParam);
			
			var curMenu = $(rootMenu).menu('findItem',e.name);
			if(e.child && e.child.length>0){
				$.each(e.child,function(ci,ce){
					
					if(window.console){
							console.log('init child menu ...')
						}
						//判断是否菜单类型
						if(ce && ce.type=='F'){
							$(rootMenu).menu('appendItem', {
								parent:curMenu.target,
								text: ce.name,						
								id:ce.fullBizcode
							});
							public_method.setModuConf(ce.fullBizcode,ce);
							public_method.setModuleNameConfig($.trim(ce.name),ce.fullBizcode)
						}
				});
			}			
		}
		
		,
		
		
		
		/**
		 * 初始化活动菜单项目
		 */
		initActiveMenu:function(){
			
			if(window.console){
				console.log(' active user menu ...');
			}
			var rootMenu = $('#activeUserMenu');
			
			//获取菜单配置		
			//获取页面站点
			var _sitePath = window.location.pathname;
			
			var _sp = _sitePath.split('/');
			
			//设置默认站点
			var _site = 'honest';
			if(window.console){
				console.log('site check ...');
			}
			if(_sp.length>=2){
				var _site = _sp[1];
				if(_site && _site.indexOf('get')<0){					
					_site = _sp[1];
				}
			}
			
			activeMenuitems = [
					{text:'廉洁风险防控系统',id:'honest',href:'/honest/main.action?site=honest'},
						{text:'协同办公系统',id:'oa',href:'/oa/main.action?site=oa'},
						{separator: true},
							{text:'修改密码',id:'password',onclick:private_method.savePassword},
							{text:'退出系统',id:'quit',href:'/biz/logout.action'}]
			
			if(activeMenuitems && activeMenuitems.length>0){
				$.each(activeMenuitems,function(ci,ce){
					$(rootMenu).menu('appendItem', ce);					
				});
			}
			
			
		},
		
		getUserInfo:function(){				
			var _opt = {
				url : '/'+rootPath+getCurrentUserUrl,					
				callback : private_method.setUserName					
			};

			ajaxServ.runAjax(_opt);				
			
		},
		setUserName:function(data){
			if(data){
				currentUser = data;				
        		$('#activeUser').menubutton({text:"当前用户:" + data.name});
			}
		},
		userMenuClick:function(evt){
			
			var _text = evt.text;
			var _logoutUrl = '/'+rootPath+logoutUrl
			if((_text!=null)&&($.trim(_text).length>0)){
				if($.trim(_text)=='退出系统'){
					var _opt = {
						url : '/'+rootPath + evt.href,					
						callback : private_method.logout					
					};
	
					ajaxServ.runAjax(_opt);
				}else{
					
					if(evt && evt.href){						
//						window.open( evt.href);		
						window.location.href=evt.href;
					}
				}
			}
		},
		logout:function(data){
			if(data && data.msg){
				window.location.href='/'+data.msg ;
			}else{
				window.location.href='/'+rootPath;
			}
			
		}
		
		,
		
		/**
		 * 检测系统配置
		 */
		checkViewPortConfig:function(_options){
			var _defaultConfig={
				height:null
			}
			
			var _dc = $.extend({},_defaultConfig,_options);
			//
			if(_dc.height){
				if(_dc.height>=900){
					pageRows = 20;
				}else{
					if(_dc.height<700){
						pageRows = 10;
					}
				}
			}
		}
	};
	
    
	/*
	 * 模块代码:模块配置
	 */
	var moduleConf = {}
	
	/*
	 * 模块名称:模块代码
	 */
	var moduleNameConf={}
	
	var public_method = {
		
		deptUserSelect:function(){
			commonSelect.deptUserSelect({rootPath:rootPath})				
		},
		
		deptSelect:function(){
			commonSelect.deptSelect({rootPath:rootPath})			
		},
		
		deptPatientSelect:function(){
			commonSelect.deptPatientSelect({rootPath:rootPath})				
		},
		
		deptOutpatientSelect:function(){
			commonSelect.deptOutpatientSelect({rootPath:rootPath})			
		},
		
		dutiesInfoSelect:function(){
			commonSelect.dutiesInfoSelect({rootPath:rootPath})				
		},
		dutiesInquiryInfoSelect:function(){
			commonSelect.dutiesInquiryInfoSelect({rootPath:rootPath})				
		},
		
		medicalInfoSelect:function(){
			commonSelect.medicalInfoSelect({rootPath:rootPath})				
		},
		
		medicalInpatientItemFeeSelect:function(){
			commonSelect.medicalInpatientItemFeeSelect({rootPath:rootPath})				
		},
		
		medicalOutpatientItemFeeSelect:function(){
			commonSelect.medicalOutpatientItemFeeSelect({rootPath:rootPath})				
		},
		supplyDetail:function(){
			commonSelect.supplyInquirySupplyDetail({rootPath:rootPath})				
		},
		
		supplySelect:function(){
			commonSelect.supplySelect({rootPath:rootPath})				
		},
		uploadSelect:function(){
			commonSelect.uploadSelect({rootPath:rootPath})				
		},		
		supplyInquirySelect:function(){
			commonSelect.supplyInquirySelect({rootPath:rootPath})				
		},
		satisRankSelect:function(){
			commonSelect.satisRankSelect({rootPath:rootPath})				
		},		
		/**
		 * 获取当前选中tab页
		 */
		getCurrentTab:function(){
			return $(menuTab).tabs('getSelected');

		},
		/**
		 * @param modu_fullBizcode 模块代码
		 * @param modu_config	模块配置
		 * @return 设置指定代码模块配置信息
		 */
		setModuConf:function(modu_fullBizcode,modu_config){
			moduleConf[modu_fullBizcode]=modu_config
		},
		/**
		 * @param modu_name 业务代码
		 * @return 返回指定代码模块配置
		 */
		getModuConf:function(modu_fullBizcode){
			return moduleConf[modu_fullBizcode]
		},
		/**
		 * @param curUser 当前登录用户
		 */
		setCurrentUser:function(curUser){
			currentUser=curUser;
		},
		/**
		 * @return 当前登录用户
		 */
		getCurrentUser:function(){
			return currentUser;
		},
		/**
		 * 
		 */
		setModuleNameConfig:function(moduName,moduFullbizcode){
			moduleNameConf[moduName]=moduFullbizcode
		},
		/**
		 * 根据模块名称获取模块配置
		 */
		getModuConfigByName:function(moduName){
			var _fullBizcode = moduleNameConf[moduName]
			if(_fullBizcode)
				return moduleConf[_fullBizcode]
			else
				return 
		},
		
		/**
		 * 获取当前业务模块代码全称
		 */
		getCurrentBizcode:function(){
			return currentBizcode;
		},
		
		setCurrentBizcode:function(fullbizcode){
			currentBizcode = fullbizcode;
		},
		/**
		 * 获取当前业务模块配置信息
		 */
		getCurrentModuConfig:function(){
			return moduleConf[this.getCurrentBizcode()]
		},
		
		/**
		 * 设置当前业务模块配置信息
		 */
		setCurrentModuConfig:function(modu_config){
			var modu_fullBizcode = this.getCurrentBizcode()
			moduleConf[modu_fullBizcode]=modu_config			
		},
		getCurrentTitle:function(){
			return currentTitle;
		},
		getRootPath:function(){
			return rootPath;
		}
		,
		
		/**
		 * 页面行数
		 */
		getPageRows:function(){
			return pageRows;
		}
		,
		setPageRows:function(data){
			if(data){
				pageRows = data;
			}
		}
		,
		
		/**
		 * 主页面初始化函数
		 */
		domReady:function (doc) {
		
			$.messager.progress({				
				msg:'loading...',
				interval:1000
			});
			if (window.console) {
	        	console.info('main modules gets ready and  been loaded.');
			}
		
		
	        var patharr = doc.location.pathname.split('/')
	        rootPath = patharr[1]
	        
	        var fullpath =window.location.protocol +'//'+window.location.host + '/'+rootPath
	        //设置ckeditor base_path
	        var basepath = '/'+rootPath +'/js/lib/common/ckeditor'
	//		window.CKEDITOR_BASEPATH = basepath
			
	//		if(CKEDITOR){
	//			CKEDITOR.basePath = basepath
	//			CKEDITOR.resourceManager.basePath = basepath
	//			CKEDITOR.stylesSet.basePath=basepath
	//			CKEDITOR.plugins.basePath=basepath
	//		}
			var org_name = commonServ.getHostpital()
		    var _orgEl = $("#mainTitle span.hospital-name")
		    $(_orgEl).text(org_name)
       
        
	        private_method.getUserInfo();
	        	
	        $userMenu = $(doc).find('#activeUserMenu');
	        
	        
	        //获取menuConfig
	        
	        //生成menu
	        var _item
	        _item = [
	        	{
		        	text: '风险防控系统',						
					id:'honest'
		        },
		        {
		        	text: '协同办公系统',						
					id:'oa'
		        },
		        {
		        	text: '风险防控系统',						
					id:'honest'
		        }
	        ]
	        $($userMenu).menu('appendItem', _item);
//	        $userMenu.append(' <div data-options="iconCls:\'myIcon-zydf-zpdf\'"url="/honest/main.action"></div>'+
//            				'<div data-options="iconCls:\'myIcon-zydf-zpdf\'" url="/oa/main.action"></div>'+
//            				'<div class="menu-sep"></div>'+
//           					'<div data-options="iconCls:\'myIcon-door-in\'">退出系统</div>')
           
	        
	        $userMenu.menu({'onClick':private_method.userMenuClick});
        
//        $ma=$("#menuAccordion");
//		$ma.accordion({animate:true,fit:true,border:false});
	        var _permissionUrl = '/'+this.getRootPath()+permissionUrl;
			$.post(_permissionUrl, null, function(rsp) {
	//			$.each(rsp,function(index,element){private_method.menuInitBootstrap(index,element)});
				
				
				$.each(rsp,function(index,element){private_method.initStartMenu(index,element)});
				
				var _options = $('#main-mm').menu('options')
				_options.onClick = private_method.menuItemClick
				var _options = $('#main-menubtn').menubutton('options')
				
	//			$("#menuAccordion a.accordion-btn").bind('click',function(e){
	//				private_method.accordionClick(e)
	//			})
				
				
				
			}, "JSON").error(function() {
				msgServ.Msgslide("获取菜单出错,请重新登录")
				window.location.href = '/' +public_method.getRootPath();
				return
			});	
		
			//初始化右侧菜单
			private_method.initActiveMenu();
			
			menuTab = $(doc).find('#centerTabs')
			$(menuTab).tabs({
				tools : [ {
						iconCls : 'icon-reload',
						handler : function() {
							var href = $('#centerTabs').tabs('getSelected').panel('options').href;
							if (href) {/*说明tab是以href方式引入的目标页面*/
								var index = $('#centerTabs').tabs('getTabIndex', $('#centerTabs').tabs('getSelected'));
								$('#centerTabs').tabs('getTab', index).panel('refresh');
							} else {   /*说明tab是以content方式引入的目标页面*/
								var panel = $('#centerTabs').tabs('getSelected').panel('panel');
								var frame = panel.find('iframe');
								try {
									if (frame.length > 0) {
										for ( var i = 0; i < frame.length; i++) {
											frame[i].contentWindow.document.write('');
											frame[i].contentWindow.close();
											frame[i].src = frame[i].src;
										}
										if ($.browser.msie) {
											CollectGarbage();
										}
									}
								} catch (e) {
								}
							}
						}
					}, {
						iconCls : 'icon-cancel',
						handler : function() {
							var index = $('#centerTabs').tabs('getTabIndex', $('#centerTabs').tabs('getSelected'));
							var tab = $('#centerTabs').tabs('getTab', index);
							if (tab.panel('options').closable) {
								$('#centerTabs').tabs('close', index);
							} else {
								$.messager.alert('提示', '[' + tab.panel('options').title + ']不可以被关闭', 'error');
							}
	         			}
	        		},{
	        		   iconCls:'icon-color',
	                   handler:function(){
		                   $('#theme').menu({   
								onClick:function(item){   
		                        var cookiesColor1=jqueryUtil.cookies.get("cookiesColor");
		                        	if(cookiesColor1!=item.id){
										jqueryUtil.cookies.set("cookiesColor",item.id,30);
										jqueryUtil.chgSkin(item.id,cookiesColor1);
		                            }
								}   
								});
		                    $('#theme').menu('show', {   
									 left: '91%',   
									 top: 97   
							});
		                    }
	        		}],
					fit : true,
					border : false,
					onContextMenu : function(e, title) {
						e.preventDefault();
						tabsMenu.menu('show', {
							left : e.pageX,
							top : e.pageY
						}).data('tabTitle', title);
					},
					onClose:private_method.closeTabs,
					onSelect:function(title,index){
						if(title){
							currentTitle = title
							currentBizcode=moduleNameConf[$.trim(title)]
						}
					}
	
				});
			private_method.checkViewPortConfig();
			$.messager.progress('close')
				
    }

	};
	
	return public_method

});